//
//  NSDate+FQDExtension.m
//  FakeQDaily
//
//  Created by mewxiv on 8/15/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "NSDate+FQDExtension.h"

@implementation NSDate (FQDExtension)

- (NSString *)dateStringSinceNow
{
    NSTimeInterval passedTime = -[self timeIntervalSinceNow];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSInteger year = [calendar component:NSCalendarUnitYear fromDate:self];
    NSInteger nowYear = [calendar component:NSCalendarUnitYear fromDate:[NSDate date]];
    
    NSString *dateString = nil;
    if (passedTime < 30 * 60) {
        dateString = @"刚刚";
    }
    else if ((passedTime /= 60) < 60) {
        dateString = [NSString stringWithFormat:@"%.f分钟前", passedTime];
    }
    else if ((passedTime /= 60) < 6) {
        dateString = [NSString stringWithFormat:@"%.f小时前", passedTime];
    }
    else if (passedTime < 24) {
        dateString = [NSString stringWithFormat:@"%.f小时前", passedTime];
    }
    else if ((passedTime /= 24) < 2) {
        dateString = @"昨天";
    }
    else if (year == nowYear ) {
        NSDateFormatter *dateFormatter = [[self class] fqd_dateStringFormatter];
        [dateFormatter setDateFormat:@"M月d日"];
        dateString = [dateFormatter stringFromDate:self];
    }
    else if (year == nowYear - 1) {
        dateString = @"去年";
    }
    else {
        NSDateFormatter *dateFormatter = [[self class] fqd_dateStringFormatter];
        [dateFormatter setDateFormat:@"yyyy年MM月dd日"];
        dateString = [dateFormatter stringFromDate:self];
    }
    
    return dateString;
}

+ (NSDateFormatter *)fqd_dateStringFormatter
{
    static NSDateFormatter *dateFormatter = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dateFormatter = [[NSDateFormatter alloc] init];
    });
    return dateFormatter;
}

@end
